//
//  LoginVC.m
//  AAPowerApp
//
//  Created by 李恺然 on 2018/11/24.
//  Copyright © 2018 Karl. All rights reserved.
//

#import "LoginVC.h"
#import "UIView+YYAdd.h"
#import "AppManager.h"
#import "ViewController.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "ConfigModel.h"
#import "WZSwitch.h"

#define DEVICE_IS_IPAD (UIUserInterfaceIdiomPad == UI_USER_INTERFACE_IDIOM())
#define kScaledValue(value) (DEVICE_IS_IPAD?(value*1.5):value)

@interface LoginVC ()
@property (nonatomic, strong) UIView *loginView;
@property (nonatomic, strong) UIImageView *bgView;
@property (nonatomic, strong) UIImageView *earthView;
@property (nonatomic, strong) UILabel *copyrightLab;
@property (nonatomic, strong) UIImageView *robotView;
@property (nonatomic, strong) UIImageView *logoView;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) UIView *usernameView;
@property (nonatomic, strong) UIView *pswView;
@property (nonatomic, strong) UITextField *userInput;
@property (nonatomic, strong) UITextField *pswInput;
@property (nonatomic, strong) WZSwitch *languageSwitch;
@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupViews];
}

- (void)setupViews{
    [self.view addSubview:self.bgView];
    [self.bgView addSubview:self.earthView];
    [self.bgView addSubview:self.copyrightLab];
    [self.bgView addSubview:self.loginView];
    [self.bgView addSubview:self.languageSwitch];
}

- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    _copyrightLab.bottom = self.view.height - kScaledValue(15);
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)noti{
    NSDictionary *userInfo = [noti userInfo];
    
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView animateWithDuration:animationDuration animations:^{
        self.bgView.frame = CGRectMake(0, -keyboardRect.size.height + (self.view.height - self.loginView.bottom), self.bgView.bounds.size.width, self.bgView.bounds.size.height);
    }];
    //self.view.bounds.size.height - _passwordInput.frame.origin.y - _passwordInput.frame.size.height -20
}
- (void)keyboardWillHide:(NSNotification *)noti{
    // 获取通知信息字典
    NSDictionary* userInfo = [noti userInfo];
    
    // 获取键盘隐藏动画时间
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView animateWithDuration:animationDuration animations:^{
        self.bgView.frame = CGRectMake(0, 0, self.bgView.bounds.size.width, self.bgView.bounds.size.height);
    }];
}

- (void)loginAction:(id)sender{
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];

    [[AppManager sharedManager] loginWithUserName:_userInput.text.copy psw:_pswInput.text.copy competedHandler:^(NSError *error) {
        if (error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                MBProgressHUD *hud = [MBProgressHUD HUDForView:[UIApplication sharedApplication].keyWindow];
                hud.label.text = error.localizedDescription;
                hud.mode = MBProgressHUDModeText;
                [hud hideAnimated:YES afterDelay:2.0];
                return;
            });
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                MBProgressHUD *hud = [MBProgressHUD HUDForView:[UIApplication sharedApplication].keyWindow];
                hud.label.text = @"Login successed";
                hud.mode = MBProgressHUDModeText;
                [hud hideAnimated:YES afterDelay:2.0];
                AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                ViewController *vc = [[ViewController alloc] init];
                [delegate.window setRootViewController:vc];
            });
        }
    }];
}

- (void)bgViewTapAction:(id)sender{
    [self.view endEditing:YES];
    [self.loginBtn endEditing:YES];
}

- (UIView *)p_createTextFieldViewWithIcon:(NSString *)icon placeHolder:(NSString *)placeHolder tag:(NSString *)tag{
    
    UIImage *widthImg = [UIImage imageNamed:@"login_btn_bg"];
    UIView *textV = [UIView new];
    textV.width = kScaledValue(widthImg.size.width);
    textV.height = kScaledValue(32);
    textV.backgroundColor = [UIColor whiteColor];
    textV.layer.masksToBounds = YES;
    textV.layer.cornerRadius = kScaledValue(8);
    
    UIImageView *img = [UIImageView new];
    img.image = [UIImage imageNamed:icon];
    [img sizeToFit];
    img.centerY = textV.height / 2;
    img.left = img.top;
    [textV addSubview:img];
    
    UITextField *textF = [UITextField new];
    textF.textColor = [UIColor darkTextColor];
    textF.borderStyle = UITextBorderStyleNone;
    textF.placeholder = placeHolder;
    textF.height = textV.height;
    textF.width = textV.width - textV.height;
    textF.left = textV.height;
    textF.top = 0;
    [textV addSubview:textF];
    
    if ([tag isEqualToString:@"username"]) {
        _userInput = textF;
    }else if ([tag isEqualToString:@"psw"]){
        _pswInput = textF;
        _pswInput.secureTextEntry = YES;
    }
    
    return textV;
}

- (UIImageView *)bgView{
    if (!_bgView) {
        _bgView = [UIImageView new];
        _bgView.frame = self.view.bounds;
        _bgView.contentMode = UIViewContentModeScaleAspectFill;
        _bgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"login_bg" ofType:@"jpg"]];
        _bgView.userInteractionEnabled = YES;
        [_bgView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bgViewTapAction:)]];
    }
    return _bgView;
}

- (WZSwitch *)languageSwitch{
    if (!_languageSwitch) {
        _languageSwitch = [[WZSwitch alloc] initWithFrame:CGRectMake(0, 0, 96, 36)];
        [_languageSwitch setSwitchState:[self getCurrentLanguage] animation:NO];
        [_languageSwitch setTextFont:[UIFont boldSystemFontOfSize:14]];
        
        __weak typeof(self) weak_self = self;
        _languageSwitch.block = ^(BOOL state) {
            if (state) {
                [AppManager sharedManager].userLanguage = UserLanguageChn;
            }else{
                [AppManager sharedManager].userLanguage = UserLanguageEng;
            }
            [weak_self updateUI];
        };
        _languageSwitch.top = kScaledValue(20);
        _languageSwitch.right = self.bgView.width - kScaledValue(20);
    }
    return _languageSwitch;
}

- (UIView *)loginView{
    if (!_loginView) {
        _loginView = [UIView new];
        _loginView.frame = CGRectMake(0, 0, kScaledValue(392), kScaledValue(118));
        _loginView.backgroundColor = [UIColor clearColor];
        
        [_loginView addSubview:self.robotView];
        [_loginView addSubview:self.logoView];
        
//        _loginView.width = _logoView.width + _robotView.width;
        _loginView.height = _robotView.height + _robotView.top;
        
        [_loginView addSubview:self.usernameView];
        [_loginView addSubview:self.pswView];
        [_loginView addSubview:self.loginBtn];
        
        _loginView.centerX = self.view.width / 2;
        _loginView.top = kScaledValue(44);
        if (DEVICE_IS_IPAD) {
            _loginView.centerY = self.view.height / 2 - kScaledValue(44);
        }
    }
    return _loginView;
}

- (UIButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [UIButton new];
        [_loginBtn setBackgroundImage:[UIImage imageNamed:@"login_btn_bg"]
                             forState:UIControlStateNormal];
        [_loginBtn setTitle:[self getLoginBtnTitle] forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor whiteColor]
                        forState:UIControlStateNormal];
        [_loginBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:kScaledValue(17)]];
        [_loginBtn setTitleEdgeInsets:UIEdgeInsetsMake(-8, -8, 0, 0)];
        [_loginBtn addTarget:self action:@selector(loginAction:)
            forControlEvents:UIControlEventTouchUpInside];
        [_loginBtn sizeToFit];
        if (DEVICE_IS_IPAD) {
            _loginBtn.width *= 1.5;
            _loginBtn.height *= 1.5;
        }
        _loginBtn.left = _usernameView.left;
        _loginBtn.top = _pswView.bottom + kScaledValue(10);
    }
    return _loginBtn;
}

- (UIView *)usernameView{
    if (!_usernameView) {
        _usernameView = [self p_createTextFieldViewWithIcon:@"login_username_icon"
                                                placeHolder:[self getUserInputPlaceHolder] tag:@"username"];
        _usernameView.left = _robotView.right + kScaledValue(10);
        _usernameView.top = _logoView.bottom - kScaledValue(10);
    }
    return _usernameView;
}

- (UIView *)pswView{
    if (!_pswView) {
        _pswView = [self p_createTextFieldViewWithIcon:@"login_passwork_icon"
                                           placeHolder:[self getPwdInputPlaceHolder] tag:@"psw"];
        _pswView.left = _usernameView.left;
        _pswView.top = _usernameView.bottom + kScaledValue(10);
    }
    return _pswView;
}

- (UIImageView *)logoView{
    if (!_logoView) {
        _logoView = [UIImageView new];
        _logoView.image = [UIImage imageNamed:@"login_aapower_logo"];
        [_logoView sizeToFit];
        if (DEVICE_IS_IPAD) {
            _logoView.width *= 1.5;
            _logoView.height *= 1.5;
        }
        _logoView.left = _robotView.right - kScaledValue(20);
        _logoView.top = 0;
    }
    return _logoView;
}

- (UIImageView *)robotView{
    if (!_robotView) {
        _robotView = [UIImageView new];
        _robotView.image = [UIImage imageNamed:@"login_robot"];
        [_robotView sizeToFit];
        if (DEVICE_IS_IPAD) {
            _robotView.width *= 1.5;
            _robotView.height *= 1.5;
        }
        _robotView.left = 0;
        _robotView.top = kScaledValue(18);
    }
    return _robotView;
}

- (UIImageView *)earthView{
    if (!_earthView) {
        _earthView = [UIImageView new];
        [_earthView setImage:[UIImage imageNamed:@"login_earth"]];
        [_earthView sizeToFit];
        if (DEVICE_IS_IPAD) {
            _earthView.width *= 1.5;
            _earthView.height *= 1.5;
        }
        _earthView.bottom = self.view.height;
        _earthView.centerX = self.view.width / 2;
    }
    return _earthView;
}

- (UILabel *)copyrightLab{
    if (!_copyrightLab) {
        _copyrightLab = [UILabel new];
        _copyrightLab.text = [NSString stringWithFormat:@"Copyright©%@ Smart Education. All Right Reserved.",[self getCurrentYear]];
        _copyrightLab.font = [UIFont boldSystemFontOfSize:kScaledValue(12)];
        _copyrightLab.textColor = [UIColor whiteColor];
        [_copyrightLab sizeToFit];
        _copyrightLab.centerX = self.view.width / 2;
        _copyrightLab.bottom = self.view.height - kScaledValue(15);
    }
    return _copyrightLab;
}

- (void)updateUI{
    _pswInput.placeholder = [self getPwdInputPlaceHolder];
    _userInput.placeholder = [self getUserInputPlaceHolder];
    [_loginBtn setTitle:[self getLoginBtnTitle] forState:UIControlStateNormal];
}

- (BOOL)getCurrentLanguage{
    switch ([AppManager sharedManager].userLanguage) {
        case UserLanguageEng:
                   return NO;
               case UserLanguageChn:
                   return YES;
    }
    return NO;
}

- (NSString *)getUserInputPlaceHolder{
    if ([AppManager sharedManager].config) {
        switch ([AppManager sharedManager].userLanguage) {
            case UserLanguageEng:
                       return [AppManager sharedManager].config.login_user_en;
                   case UserLanguageChn:
                       return [AppManager sharedManager].config.login_user_cn;
        }
    }
    return @"Student ID";
}

- (NSString *)getPwdInputPlaceHolder{
    if ([AppManager sharedManager].config) {
        switch ([AppManager sharedManager].userLanguage) {
            case UserLanguageEng:
                       return [AppManager sharedManager].config.login_password_en;
                   case UserLanguageChn:
                       return [AppManager sharedManager].config.login_password_cn;
        }
    }
    return @"Password";
}

- (NSString *)getLoginBtnTitle{
    if ([AppManager sharedManager].config) {
        switch ([AppManager sharedManager].userLanguage) {
            case UserLanguageEng:
                return [AppManager sharedManager].config.login_text_en;
            case UserLanguageChn:
                return [AppManager sharedManager].config.login_text_cn;
        }
    }
    return @"LOGIN";
}

- (NSString *)getCurrentYear{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy"];
    return [formatter stringFromDate:date];
}

- (BOOL)shouldAutorotate
{
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

@end
